import { useEffect, useState } from "react"
import fetch from "cross-fetch"

function useFecth(url, options) {

    const [loading, setLoading] = useState(false)
    const [data, setData] = useState("")
    const [err, setErr] = useState("")

    // 一旦url或者options发生变化 就重新加载数据
    useEffect(
        () => {
            setLoading(true)

            fetch(url, options)
                .then(res => res.text())
                .then(data => setData(data))
                .catch(err => setErr(err))
                .finally(() => setLoading(false))
        },
        [url, options]
    )

    return [loading, data, err]
}

function UseFetchDemo({ url, options }) {

    const [loading, data, err] = useFecth(url, options)

    return (
        <div>
            UseFetchDemo
            <br />

            {loading ? "Loading..." : "loaded"}
            <br />

            data={data ? data : "pending..."}
            <br />

            err={err ? JSON.stringify(err) : "null"}
        </div>
    )
}

export default UseFetchDemo
